﻿/***************************
* 1.团购列表
* 2.团购详情
* 3.团购预订
****************************/

/* 变量 */
var group = "booking/group.html";
var groupDetail = "booking/groupDetail.html";
var groupBooking = "booking/groupBooking.html";
var groupPay = "booking/groupPay.html";

/* 团购 */
var contactsCallback_group = myApp.onPageInit('group', function (page) {

    /* 筛选条件 */
    $$("#category_list ul li").hide();
    $$("#sel_region").show();
    $$("#sel_group_type").show();
    $$("#sel_group_price_range").show();
    $$("#sel_group_usernumber").show();

    var pickerRegion; //所在区域
    var pickerGroupType; //团购类型
    var pickerGroupPriceRange; //价格范围
    var pickerGroupUserNumber; //使用人数

    pickerRegion = myApp.picker({
        input: '#sel_region_value',
        toolbarTemplate:
        '<div class="toolbar theme-red">' +
        '<div class="toolbar-inner">' +
        '<div class="left"></div>' +
        '<div class="right">' +
        '<a href="#" class="link close-picker">确定</a>' +
        '</div>' +
        '</div>' +
        '</div>',
        formatValue: function (p, values, displayValues) {
            return displayValues;
        },
        cols: [
            {
                textAlign: 'center',
                values: (function () {
                    var arrValue = [];
                    $$.each(iss_dictionaryBaseData.district(), function (i, obj) {
                        arrValue.push(obj.value);
                    });
                    return arrValue;
                })(),
                displayValues: (function () {
                    var arrDisplay = [];
                    $$.each(iss_dictionaryBaseData.district(), function (i, obj) {
                        arrDisplay.push(obj.display);
                    });
                    return arrDisplay;
                })()
            }
        ]
    });

    pickerGroupType = myApp.picker({
        container: true,
        input: '#sel_group_type_value',
        toolbarTemplate:
        '<div class="toolbar theme-red">' +
        '<div class="toolbar-inner">' +
        '<div class="left"></div>' +
        '<div class="right">' +
        '<a href="#" class="link close-picker">确定</a>' +
        '</div>' +
        '</div>' +
        '</div>',
        formatValue: function (p, values, displayValues) {
            return displayValues;
        },
        cols: [
            {
                textAlign: 'center',
                values: (function () {
                    var arrValue = [];
                    $$.each(iss_dictionaryBaseData.groupType(), function (i, obj) {
                        arrValue.push(obj.value);
                    });
                    return arrValue;
                })(),
                displayValues: (function () {
                    var arrDisplay = [];
                    $$.each(iss_dictionaryBaseData.groupType(), function (i, obj) {
                        arrDisplay.push(obj.display);
                    });
                    return arrDisplay;
                })()
            }
        ],
    });

    pickerGroupPriceRange = myApp.picker({
        input: '#sel_group_price_range_value',
        toolbarTemplate:
        '<div class="toolbar theme-red">' +
        '<div class="toolbar-inner">' +
        '<div class="left"></div>' +
        '<div class="right">' +
        '<a href="#" class="link close-picker">确定</a>' +
        '</div>' +
        '</div>' +
        '</div>',
        formatValue: function (p, values, displayValues) {
            return displayValues;
        },
        cols: [
            {
                textAlign: 'center',
                values: (function () {
                    var arrValue = [];
                    $$.each(iss_dictionaryBaseData.groupPriceRange(), function (i, obj) {
                        arrValue.push(obj.value);
                    });
                    return arrValue;
                })(),
                displayValues: (function () {
                    var arrDisplay = [];
                    $$.each(iss_dictionaryBaseData.groupPriceRange(), function (i, obj) {
                        arrDisplay.push(obj.display);
                    });
                    return arrDisplay;
                })()
            }
        ]
    });

    pickerGroupUserNumber = myApp.picker({
        input: '#sel_group_usernumber_value',
        toolbarTemplate:
        '<div class="toolbar theme-red">' +
        '<div class="toolbar-inner">' +
        '<div class="left"></div>' +
        '<div class="right">' +
        '<a href="#" class="link close-picker">确定</a>' +
        '</div>' +
        '</div>' +
        '</div>',
        formatValue: function (p, values, displayValues) {
            return displayValues;
        },
        cols: [
            {
                textAlign: 'center',
                values: (function () {
                    var arrValue = [];
                    $$.each(iss_dictionaryBaseData.groupUseNumber(), function (i, obj) {
                        arrValue.push(obj.value);
                    });
                    return arrValue;
                })(),
                displayValues: (function () {
                    var arrDisplay = [];
                    $$.each(iss_dictionaryBaseData.groupUseNumber(), function (i, obj) {
                        arrDisplay.push(obj.display);
                    });
                    return arrDisplay;
                })()
            }
        ]
    });

    //获取页面参数
    var stype = ISS.utils.getParameter("stype");
    if (page != undefined) {
        stype = page.query.stype;
    }

    if (stype && pickerGroupType && pickerGroupType.cols.length > 0) {
        $$.each(iss_dictionaryBaseData.groupType(), function (i, obj) {
            var _type = "";
            switch (stype) {
                case 'ms':
                    _type = "美食";
                    break;
                case 'tc':
                    _type = "特产";
                    break;
                case 'yl':
                    _type = "娱乐";
                    break;
                case 'xcy':
                    _type = "乡村游";
                    break;
                default:
                    _type = "不限";
                    break;
            }
            if (obj.display == _type) {
                pickerGroupType.cols[0].setValue(obj.value);
            }
        });
    }

    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;

    var index_tab1 = 1;
    var index_tab2 = 1;
    var index_tab3 = 1;
    var index_tab4 = 1;
    var current_tabindex = 0;
    var size = 10;

    LoadGroupAll(index_tab1, size);

    //加载数据
    function LoadGroupAll(pageindex, pagesize) {

        // 检索条件
        var v_search = [];
        var v_order = [];

        var v_longitude = "";
        var v_latitude = "";

        //查询条件

        // 站点
        if (_cityCode != "") {
            var opt = {
                SearchField: "CityCode",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: _cityCode
                    }
                ]
            };
            v_search.push(opt);
        }

        // 区域
        if (pickerRegion && pickerRegion.value && pickerRegion.value.length > 0) {
            var opt = {
                SearchField: "District",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: pickerRegion.value[0]
                    }
                ]
            };
            v_search.push(opt);
        }

        //类型
        if (pickerGroupType && pickerGroupType.value && pickerGroupType.value.length > 0) {
            var opt = {
                SearchField: "ProductType",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: pickerGroupType.value[0]
                    }
                ]
            };
            v_search.push(opt);
        }

        //价格
        if (pickerGroupPriceRange && pickerGroupPriceRange.value && pickerGroupPriceRange.value.length > 0) {
            var opt = {
                SearchField: "PriceRange",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: pickerGroupPriceRange.value[0]
                    }
                ]
            };
            v_search.push(opt);
        }

        //使用人数
        if (pickerGroupUserNumber && pickerGroupUserNumber.value && pickerGroupUserNumber.value.length > 0) {
            var opt = {
                SearchField: "UseNumber",
                ConditionType: 1,
                AndOR: "and",
                ListSearchValue: [
                    {
                        ItemValue: pickerGroupUserNumber.value[0]
                    }
                ]
            };
            v_search.push(opt);
        }

        // 排序
        if (current_tabindex == 0) {
            var opt = {
                OrderField: "Sort",
                OrderType: "desc"
            };
            v_order.push(opt);
        }
        else if (current_tabindex == 1) {
            var opt = {
                OrderField: "ScoreOrder",
                OrderType: "desc"
            };
            v_order.push(opt);
        }
        else if (current_tabindex == 2) {
            var opt = {

                OrderField: "PriceOrder",
                OrderType: "asc"
            };
            v_order.push(opt);
        } else if (current_tabindex == 3) {
            var opt = {

                OrderField: "DistanceOrder",
                OrderType: "asc"
            };
            v_order.push(opt);
        }

        if (_isOpenPosition) {
            v_longitude = iss_localStorage.get("yuqing_longitude");
            v_latitude = iss_localStorage.get("yuqing_latitude");
        }
        else {
            v_longitude = iss_dictionaryBaseData.longitude;
            v_latitude = iss_dictionaryBaseData.latitude;
        }

        var jd_conditionParams = JSON.stringify({
            type: 0,
            conditionParams: {
                Page: {
                    PageSize: pagesize,
                    PageIndex: pageindex
                },
                Search: v_search,
                Order: v_order
            },
            lng: v_longitude,
            lat: v_latitude,

        });

        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.GROUP,
            data: { content: jd_conditionParams },
            dataType: "jsonp",
            method: "POST",
            success: function (data, status) {
                myApp.hidePreloader();
                data = JSON.parse(data);
                if(current_tabindex==0 && index_tab1==1){
                    $$("#group_tab2 #sub_tab1 .content-block ul").children("li").remove();
                }
                if(current_tabindex==1 && index_tab2==1){
                    $$("#group_tab2 #sub_tab2 .content-block ul").children("li").remove();
                }
                if(current_tabindex==2 && index_tab3==1){
                    $$("#group_tab2 #sub_tab3 .content-block ul").children("li").remove();
                }
                if(current_tabindex==3 && index_tab4==1){
                    $$("#group_tab2 #sub_tab4 .content-block ul").children("li").remove();
                }
                
                if (data && data.status == "0" && data.results.length > 0) {
                    // 数据格式化
                    for (var i = 0; i < data.results.length; i++) {
                        //                        if (data.results[i].getImage && (data.results[i].getImage.smallImageFrontUrl == undefined ||
                        //                            data.results[i].getImage.smallImageFrontUrl == null || data.results[i].getImage.smallImageFrontUrl == "")) {
                        //                            data.results[i].getImage.smallImageFrontUrl = NoPicture();
                        //                        };
                        data.results[i] = getDefaultImg(data.results[i]);
                        // 评分
                        data.results[i].colligationScore = formatScore(data.results[i].colligationScore);
                        // 距离
                        data.results[i].distance = ISS.utils.toFixed(data.results[i].distance, 2);
                    };
                    // 模板
                    var searchTemplate = $$('#template-group-tab2').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data);
                        if (current_tabindex == 0) $$("#group_tab2 #sub_tab1 .content-block ul").append(html);
                        if (current_tabindex == 1) $$("#group_tab2 #sub_tab2 .content-block ul").append(html);
                        if (current_tabindex == 2) $$("#group_tab2 #sub_tab3 .content-block ul").append(html);
                        if (current_tabindex == 3) $$("#group_tab2 #sub_tab4 .content-block ul").append(html);
                        flag_InfiniteScroll = flag_needScroll = true;
                    }

                    //tab1综合,无限滚动只加载一次
                    if (!flag_execute) {
                        //只执行一次
                        flag_execute = true;

                        // 加载flag
                        var loading = false;

                        $$('.infinite-scroll').on('infinite', function () {
                            //综合 价格 距离 切换
                            if (!flag_needScroll) {
                                flag_needScroll = true;
                                return;
                            }

                            //查询时,删除滚动后重新绑定pageindex
                            if (!flag_InfiniteScroll) {
                                flag_InfiniteScroll = true;
                                return;
                            }

                            if (true) {
                                // 如果正在加载，则退出
                                if (loading) return;
                                // 设置flag
                                loading = true;
                                // 模拟1s的加载过程
                                setTimeout(function () {
                                    // 重置加载flag
                                    loading = false;
                                    if (current_tabindex == 0) {
                                        index_tab1++;
                                        LoadGroupAll(index_tab1, pagesize);
                                    }
                                    else if (current_tabindex == 1) {
                                        index_tab2++;
                                        LoadGroupAll(index_tab2, pagesize);
                                    }
                                    else if (current_tabindex == 2) {
                                        index_tab3++;
                                        LoadGroupAll(index_tab3, pagesize);
                                    }
                                    else if (current_tabindex == 3) {
                                        index_tab4++;
                                        LoadGroupAll(index_tab4, pagesize);
                                    }
                                }, 100);
                            }
                        });

                    }
                    if (current_tabindex == 0 && $$("#group_tab2 #sub_tab1 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader1').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                    else if (current_tabindex == 1 && $$("#group_tab2 #sub_tab2 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader2').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                    else if (current_tabindex == 2 && $$("#group_tab2 #sub_tab3 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader3').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                    else if (current_tabindex == 3 && $$("#group_tab2 #sub_tab4 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader4').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                }
                else {
                    // 删除加载提示符
                    myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    if (current_tabindex == 0) {
                        $$('.infinite-scroll-preloader1').remove();
                        // 删除多余的提示
                        $$("#group_tab2 #sub_tab1 .content-block .noAnswer").remove();
                        if (pageindex == 1)
                            $$("#group_tab2 #sub_tab1 .content-block").append("<div id='noAnswer' style='margin:auto;text-align:center'>对不起，您搜索的结果不存在！</div>");
                    }
                    else if (current_tabindex == 1) {
                        $$('.infinite-scroll-preloader2').remove();
                        // 删除多余的提示
                        $$("#group_tab2 #sub_tab2 .content-block .noAnswer").remove();
                        if (pageindex == 1)
                            $$("#group_tab2 #sub_tab2 .content-block").append("<div id='noAnswer' style='margin:auto;text-align:center'>对不起，您搜索的结果不存在！</div>");
                    }
                    else if (current_tabindex == 2) {
                        $$('.infinite-scroll-preloader3').remove();
                        // 删除多余的提示
                        $$("#group_tab2 #sub_tab3 .content-block .noAnswer").remove();
                        if (pageindex == 1)
                            $$("#group_tab2 #sub_tab3 .content-block").append("<div id='noAnswer' style='margin:auto;text-align:center'>对不起，您搜索的结果不存在！</div>");
                    }
                    else if (current_tabindex == 3) {
                        $$('.infinite-scroll-preloader4').remove();
                        // 删除多余的提示
                        $$("#group_tab2 #sub_tab4 .content-block .noAnswer").remove();
                        if (pageindex == 1)
                            $$("#group_tab2 #sub_tab4 .content-block").append("<div id='noAnswer' style='margin:auto;text-align:center'>对不起，您搜索的结果不存在！</div>");
                    }
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                myApp.alert("服务器连接失败！");
            }
        });
    };

    //查询条件
    $$(".view-right .right a.close-panel").on("click", function () {
        myApp.attachInfiniteScroll($$('.infinite-scroll'));
        $$("#group_tab2 #sub_tab1 .content-block ul").children("li").remove();
        $$("#group_tab2 #sub_tab2 .content-block ul").children("li").remove();
        $$("#group_tab2 #sub_tab3 .content-block ul").children("li").remove();
        $$("#group_tab2 #sub_tab4 .content-block ul").children("li").remove();
        $$(".noAnswer").remove();
        myApp.showPreloader();

        flag_InfiniteScroll = false;
        flag_needScroll = true;
        index_tab1 = index_tab2 = index_tab3 = index_tab4 = 1;
        if (current_tabindex == 0)
            LoadGroupAll(index_tab1, size);
        else if (current_tabindex == 1)
            LoadGroupAll(index_tab2, size);
        else if (current_tabindex == 2)
            LoadGroupAll(index_tab3, size);
        else if (current_tabindex == 3)
            LoadGroupAll(index_tab4, size);
    });

    //综合 价格 距离切换
    $$(".subnavbar").on("click", "a", function () {
        $$('.infinite-scroll').scrollTop(0);
        current_tabindex = $$(this).index();
        myApp.attachInfiniteScroll($$('.infinite-scroll'));

        flag_InfiniteScroll = true;
        flag_needScroll = false;
        if ($$(this).index() == 0 && $$("#group_tab2 #sub_tab1 .content-block ul").children("li").length == 0) {
            LoadGroupAll(index_tab1, size);
        }
        else if ($$(this).index() == 1 && $$("#group_tab2 #sub_tab2 .content-block ul").children("li").length == 0) {
            LoadGroupAll(index_tab2, size);
        }
        else if ($$(this).index() == 2 && $$("#group_tab2 #sub_tab3 .content-block ul").children("li").length == 0) {
            LoadGroupAll(index_tab3, size);
        }
        else if ($$(this).index() == 3 && $$("#group_tab2 #sub_tab4 .content-block ul").children("li").length == 0) {
            LoadGroupAll(index_tab4, size);
        }
    });
});

/* 团购详情  */
var contactsCallback_groupDetail = myApp.onPageInit('groupDetail', function (page) {
    //获取页面参数
    var code = ISS.utils.getParameter("code");
    if (page != undefined) {
        code = page.query.code;
    }

    var _content = JSON.stringify({
        type: 1,
        Code: code
    });

    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.GROUP,
        data: { "content": _content },
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.status == "0" && data.results) {

                var searchTemplate = $$('#template-group-detail').html();
                if (searchTemplate) {
                    var compiledTemplate = Template7.compile(searchTemplate);

                    data.results = getDefaultImg(data.results);

                    var html = compiledTemplate(data.results);
                    $$("#group_detail_page .page-content").html(html);
                }
            }
        },
        error: function (xhr, status) {
            console.log("ajax error!");
        }
    });

    //预订按钮
    $$("#group_detail_page .page-content").on("click", "a.btn-booking[href='#']", function (e) {
        //取消原有跳转事件
        e.stopPropagation();
        //保存当前控件
        var mythis = $$(this);
        //跳转判断
        CheckPopLogin(function () {
            //window.location.href = mythis.attr("data-href");
            mainView.router.loadPage({ url: mythis.attr("data-href"), reload: false });
        });
    })
});

/* 团购预订  */
var contactsCallback_groupBooking = myApp.onPageInit('groupBooking', function (page) {
    //获取页面参数
    var scode = ISS.utils.getParameter("scode");
    if (page != undefined) {
        scode = page.query.scode;
    }
    var _userID = iss_localStorage.get("yuqing_appUserId"); // 全局变量
    var _cnName = "";
    var _saleprice = "0";
    var _listingPrice = "0";
    var _shopCode = "";

    //加载房型
    loadDetail();
    function loadDetail() {
        var _content = JSON.stringify({
            type: 1,
            Code: scode
        })
        myApp.showPreloader();
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.GROUP,
            data: { "content": _content },
            crossDomain: true,
            method: "POST",
            success: function (data, status) {
                data = JSON.parse(data);
                if (data && data.status == "0" && data.results) {
                    _cnName = data.results.cnName;
                    _saleprice = data.results.NEWSALEPRICE;
                    _listingPrice = data.results.NEWLISTINGPRICE;
                    _shopCode = data.results.shopCode;

                    $$("h3.booking-tit").html(data.results.cnName); // 名称
                    $$("p.original-price span").html(data.results.NEWLISTINGPRICE); // 市场价
                    $$("p.single-price span").html(data.results.NEWSALEPRICE); // 销售价格
                    SumPrice();
                    myApp.hidePreloader();
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                console.log("ajax error!");
            }
        });
    }

    //加载用户
    loadUser();
    function loadUser() {
        var _content = JSON.stringify({
            type: 13,
            user: {
                ID: iss_localStorage.get("yuqing_appUserId"),
                PhoneNumber: ""
            }
        });
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.USERINFO,
            data: { "content": _content },
            crossDomain: true,
            method: "POST",
            success: function (data, status) {

                data = JSON.parse(data);
                if (data && data.status == "0") {
                    $$(".booking-info #name").val(data.results.name); //联系人
                    $$(".booking-info #telephone").val(data.results.phoneNumber); //联系电话
                    $$(".booking-info #card").val(data.results.cardNo); //身份证号
                }
                else {
                    myApp.alert('获取用户失败!');
                }
            },
            error: function (xhr, status) {
                myApp.alert('获取用户失败!');
            }
        });
    }

    //加
    $$("div.num a.jia1").click(function () {
        if ($$(this).hasClass("unable")) return;
        var num = $$("div.num span").html();
        num = parseInt(num) + 1;
        if (num >= 99) $$(this).addClass("unable");
        $$("div.num span").html(num);
        if (num > 1) $$("div.num a.jian1").removeClass("unable");
        SumPrice();
    })
    //减
    $$("div.num a.jian1").click(function () {
        if ($$(this).hasClass("unable")) return;
        var num = $$("div.num span").html();
        num = parseInt(num) - 1;
        if (num <= 1) $$(this).addClass("unable");
        if (num < 99) $$("div.num a.jia1").removeClass("unable");
        $$("div.num span").html(num);
        SumPrice();
    })

    //计算金额
    function SumPrice() {
        var orderNumber = parseInt($$("div.num span").html());
        var sum_money = ISS.utils.toFixed(parseFloat(_saleprice) * orderNumber);
        var sum_listing_money = ISS.utils.toFixed(parseFloat(_listingPrice) * orderNumber)
        var sum_thrift_money = sum_listing_money - sum_money;
        $$("#groupBooking_page div.sum-price span.totle").html(sum_money);
        $$("#groupBooking_page div.sum-price span.thrift").html(sum_thrift_money);
    }

    $$("input[name='my-checkbox']").change(function () {
        if ($$(this).is(':checked')) {
            $$("#groupBooking_page #btnsubOrder").removeAttr("disabled");
        }
        else {
            $$("#groupBooking_page #btnsubOrder").attr("disabled", "disabled");
        }
    })

    //提交订单
    $$("#groupBooking_page #btnsubOrder").click(function () {
        var _name = $$(".booking-info #name").val(); //联系人
        var _telephone = $$(".booking-info #telephone").val(); //联系电话

        var _orderNumber = $$("div.num span").html();
        var _sumPrice = parseFloat(_saleprice) * parseInt(_orderNumber);

        if (_name == '') {
            myApp.alert("请填写您的姓名");
            return;
        }
        if (_telephone == '') {
            myApp.alert("请填写您的手机号码");
            return;
        }
        if (!/^((1[3-9])+\d{9})$/.test(_telephone)) {
            myApp.alert("请填写正确的手机号码！");
            return;
        }

        var _content = JSON.stringify({
            type: "93",
            orderSubmitEntity: {
                OrderShopEntity: [
                    {
                        ShopType: "21",
                        UserID: _userID,
                        ShopCode: _shopCode,
                        OrderName: _cnName,
                        OrderType: "22",
                        Leavemsg: "",
                        Person: _name,
                        Phone: _telephone,
                        RecommendCode: "",
                        IDCard: "",
                        OrderProductEntity: [
                            {
                                ID: "0",
                                ProductName: _cnName,
                                ProductCode: scode,
                                SalePrice: _sumPrice,
                                OrderNumber: _orderNumber,
                                PlayDate: ISS.utils.dateToStr("yyyy-MM-dd"),
                            }
                        ]
                    }
                ],
                UserID: _userID,
                Phone: _telephone,
                Source: "2",
                PayType: "2",
                TotalSalePrice: _sumPrice
            }
        });
        myApp.showPreloader();
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.GROUP,
            data: { "content": _content },
            crossDomain: true,
            method: "POST",
            success: function (data, status) {
                myApp.hidePreloader();
                data = JSON.parse(data);
                if (data && data.status == "0") {
                    //微信订单
                    var _wxcontent = JSON.stringify({
                        OrderGuid: ISS.utils.GUID(),
                        AccountGuid: iss_localStorage.get("yuqing_appAccount"),
                        UserId: _userID,
                        OrderNo: data.results,
                        OrderName: _cnName,
                        OrderType: "4", // 团购
                        OrderStatus: "2",
                        OrderNumber: _orderNumber,
                        OrderStartTime: $$("a#begindate").attr("date"),
                        OrderEndTime: $$("a#enddate").attr("date"),
                        OrderSource: "2",
                        OrderPic: "",
                        PayType: "0",
                        PayPrice: _sumPrice,
                        SumPrice: _sumPrice,
                        ReMark: "",
                        CreateTime: new Date(),
                        ModifyTime: new Date(),
                        IsDelete: "0"
                    });
                    SaveWapOrders(_wxcontent, function () {
                        var jsonData = JSON.stringify({
                            first: "预订成功",
                            order: data.results, //订单号
                            Name: _name, //入住人
                            number: _orderNumber, //房间数量
                            pay: _sumPrice, //订单总价
                            remark: "有任何疑问，请联系客服"
                        });
                        //SendTemplateMessage("HotelBookingSuccess", "", jsonData, function () {
                        mainView.router.loadPage({ url: "groupPay.html?OrderNo=" + data.results + "&OrderName=" + _cnName + "&SumPrice=" + _sumPrice, reload: false });
                        //    return;
                        //});
                    });
                    //微信订单结束
                }
                else if (data && data.status == "10") {
                    myApp.hidePreloader();
                    myApp.alert(data.message);
                }
                else {
                    myApp.hidePreloader();
                    myApp.alert('提交订单失败!');
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                myApp.alert('提交订单失败!');
            }
        });
    });
});

/* 团购待付款  */
var contactsCallback_groupPay = myApp.onPageInit('groupPay', function (page) {
    //获取页面参数
    var OrderNo = ISS.utils.getParameter("OrderNo");
    var OrderName = ISS.utils.getParameter("OrderName");
    var SumPrice = ISS.utils.getParameter("SumPrice");
    if (page != undefined) {
        OrderNo = page.query.OrderNo;
        OrderName = page.query.OrderName;
        SumPrice = page.query.SumPrice;
    }
    $$("#groupPay_page #back_booking").click(function () {
        mainView.router.back();
    })
    if (OrderNo == undefined || OrderNo == "") {
        $$("#groupPay_page #faild").show();
        $$("#groupPay_page #success").hide();
        return;
    }
    else {
        $$("#groupPay_page #success").show();
        $$("#groupPay_page #faild").hide();
    }


    var _content = JSON.stringify({
        Code: OrderNo,
        type: 1
    });
    var timer_Interval;
    myApp.showPreloader();
    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.ORDERS,
        data: { "content": _content },
        crossDomain: true,
        method: "POST",
        success: function (data, status) {
            try {
                data = JSON.parse(data);
                if (data && data.status == "0") {
                    //格式化数据
                    data.results.orderSTATUSName = "";
                    if (data.results.orderSTATUS == "1") {
                        data.results.orderSTATUSName = "待确认";
                    }
                    else if (data.results.orderSTATUS == "2") {
                        data.results.orderSTATUSName = "待付款";
                    }
                    else if (data.results.orderSTATUS == "3") {
                        data.results.orderSTATUSName = "已取消";
                    }
                    else if (data.results.orderSTATUS == "4") {
                        data.results.orderSTATUSName = "已支付";
                    }

                    //中间数据模板
                    var searchTemplate = $$('#groupPay_page #template-grouppay-tab1').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data.results);
                        $$("#groupPay_page div.card").append(html);
                    }

                    //底部总价

                    var sumPrice = data.results.sumPrice;
                    var sum_thrift_money = ISS.utils.toFixed(parseFloat(data.results.totalListingPrice) - parseFloat(sumPrice)); //总差价
                    $$("#groupPay_page div.sum-price span.totle").html(sumPrice);
                    $$("#groupPay_page div.sum-price span.thrift").html(sum_thrift_money);

                    //头部倒计时
                    //var orderTime30 = ISS.utils.strToDate("2016-06-12 15:38");
                    var orderTime30 = ISS.utils.strToDate(data.results.orderTime);
                    orderTime30 = orderTime30.setMinutes(orderTime30.getMinutes() + 30);
                    if ((orderTime30 - new Date().getTime()) > 0) {
                        $$("#groupPay_page #btnPayOrder").removeAttr("disabled");
                    }
                    if (timer_Interval != undefined) {
                        clearInterval(timer_Interval);
                    }
                    function timer() {
                        var ts = orderTime30 - new Date().getTime(); //计算剩余的毫秒数 
                        if (ts <= 0) {
                            $$("#groupPay_page #btnPayOrder").attr("disabled", "disabled");
                            if (timer_Interval != undefined) {
                                clearInterval(timer_Interval);
                            }
                            myApp.alert('支付时间已过！', function () {
                                //mainView.router.loadPage({ url: "ticketDetail.html?ticketdetail_code=" + data.results.shopNo, reload: false });
                            })
                            return;
                        }
                        var mm = parseInt(ts / 1000 / 60 % 60, 10); //计算剩余的分钟数  
                        var ss = parseInt(ts / 1000 % 60, 10); //计算剩余的秒数  
                        mm = checkTime(mm);
                        ss = checkTime(ss);
                        $$("#groupPay_page b.min").html(mm);
                        $$("#groupPay_page b.sec").html(ss);
                    }
                    timer_Interval = setInterval(timer, 1000);
                    myApp.hidePreloader();

                }
                else {
                    myApp.hidePreloader();
                    myApp.alert('参数错误!');
                }
            } catch (ex) {
                myApp.hidePreloader();
            }
        },
        error: function (xhr, status) {
            myApp.hidePreloader();
            myApp.alert('参数错误!');
        }
    });

    $$("#groupPay_page #btn_back").click(function () {
        if (timer_Interval != undefined) {
            clearInterval(timer_Interval);
        }
    })
    function checkTime(k) {
        if (k < 10) {
            k = "0" + k;
        }
        return k;
    }

    //支付
    var IsPaying = false;
    $$("#groupPay_page #btnPayOrder").click(function () {
        if (!IsPaying) {
            //标识正在支付
            IsPaying = true;
            //订单号 --- 订单名称 --- 价格 --- 类型：1：酒店 2：线路 3：门票 --- 回调函数
            WxPay.utils.UnifiedoOrder(OrderNo, '22', function (result) {
                //标识支付完成
                IsPaying = false;
                mainView.router.loadPage({ url: "payResult.html?result=" + result + "&type=22", reload: false })
            });
        }
    })
});

/* 初始化  */
function initData() {
    var href = window.location.href;
    if (href.indexOf(group) > -1) {
        contactsCallback_group.trigger();
    }
    else if (href.indexOf(groupDetail) > -1) {
        contactsCallback_groupDetail.trigger();
    }
    else if (href.indexOf(groupBooking) > -1) {
        contactsCallback_groupBooking.trigger();
    }
    else if (href.indexOf(groupPay) > -1) {
        contactsCallback_groupPay.trigger();
    }
}

initData();

